<?php
/**
 * Author: ChenGuangHui
 * Email：13035809409@163.com
 * Date Time: 2021/4/30 11:35
 */


namespace App\Logic\Activity;


use App\Enums\HttpCode;
use App\Logic\CommLogic;
use App\Models\Activity;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\QueryException;

class ActivityLogic extends CommLogic
{
    /**
     * @param array $where
     * @param array $pageData
     * @param array $sortData
     * @return \Illuminate\Http\JsonResponse
     */
    public function index($where = [], $pageData = ['pageSize' => 20, 'pageNow' => 1], $sortData = [])
    {
        $query = Activity::query()
            ->when(isset($where['status']), function (Builder $query) use ($where) {
                $query->where('status', $where['status']);
            })
            ->when(!empty($where['name']), function (Builder $query) use ($where) {
                $query->where('name', '%' . $where['name'] . '%');
            });

        if (!empty($sortData)) {
            $query = $query->orderBy($sortData['sortRow'], $sortData['sortType']);
        }

        $data = $query->paginate($pageData['pageSize'], ['*'], 'page', $pageData['pageNow'])
            ->toArray();

        return $data;
    }

    /**
     * @param $params
     * @return bool
     * @throws \Throwable
     */
    public function store($params)
    {
        $lockName = 'tenant_store_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');
        \DB::beginTransaction();
        try {
            list($valid_start, $valid_end) = $params['valid_time'];
            $data = array(
                'name' => $params['name'],
                'status' => $params['status'],
                'valid_end_at' => $valid_end,
                'valid_start_at' => $valid_start,
                'logo' => json_encode($params['logo'], true),
                'copyright' => $params['copyright'] ?? '',
                'login_background' => $params['login_background'] ?? '',
                'remark' => $params['remark'] ?? '',
            );
            Activity::query()->create($data);
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new \Exception($exception->getMessage(), $exception->getCode());
        }
        return true;
    }

    /**
     * @param $params
     * @param $id
     * @return Activity|\Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Model|object|null
     */
    public function show($params, $id)
    {
        $tenant = Activity::query()->where('id', $id)->first();
        abort_if(empty($tenant), HttpCode::FORBIDDEN, '找不到活动');
        $tenant->logo = json_decode($tenant->logo, true);
        $tenant->valid_time = array($tenant->valid_start_at, $tenant->valid_end_at);
        return $tenant;
    }

    /**
     * @param $params
     * @param $id
     * @return bool
     * @throws \Throwable
     */
    public function update($params, $id)
    {

        $lockName = 'tenant_update_' . auth('api')->id();
        $lock = \Cache::lock($lockName, 5);
        abort_if(!$lock->get(), HttpCode::TOO_MANY_REQUESTS, '请勿重复操作！');

        $tenant = Activity::query()->where('id', $id)->first();
        abort_if(empty($tenant), HttpCode::FORBIDDEN, '找不到活动');
        \DB::beginTransaction();
        try {
            
            list($valid_start, $valid_end) = $params['valid_time'];
            $data = array(
                'name' => $params['name'],
                'status' => $params['status'],
                'valid_end_at' => $valid_end,
                'valid_start_at' => $valid_start,
                'logo' => json_encode($params['logo'], true),
                'copyright' => $params['copyright'] ?? '',
                'login_background' => $params['login_background'] ?? '',
                'remark' => $params['remark'] ?? '',
            );
            $tenant->update($data);
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new \Exception($exception->getMessage(), $exception->getCode());
        }
        return true;
    }

    /**
     * @param $id
     * @return bool
     * @throws \Throwable
     */
    public function destroy($id)
    {

        $data = Activity::query()->where('id', $id)->first();
        abort_if(empty($data), HttpCode::FORBIDDEN, '找不到活动');
        \DB::beginTransaction();
        try {
            $data->delete();
            \DB::commit();
        } catch (QueryException $exception) {
            \DB::rollBack();
            throw new \Exception($exception->getMessage(), $exception->getCode());
        }
        return true;
    }
}
